<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" @click="view(row.id)" icon="el-icon-view" size="small" v-if="permission.iqcDefectHandling_detail">详情</el-button>
        <el-button type="text" @click="badHandling(row.id)" size="small" v-if="permission.iqcDefectHandling_handle">不良处理</el-button>
      </template>
    </avue-crud>
    <el-dialog :key="timer" append-to-body :visible.sync="showDialog" width="60%" class="iqcDialog" @close="closeDialog" :fullscreen="fullscreenHandlingDialog">
      <div slot="title">
        填写不良处理结果<i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenHandlingDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenHandlingDialog = !fullscreenHandlingDialog"
        ></i>
      </div>
      <avue-form ref="badhandlingProperties" v-model="model" :option="propertiesOption">
        <template slot="iqcNGAttachments">
          <el-upload
            action="/api/blade-resource/oss/endpoint/put-file-attach"
            :on-change="changeFile"
            :headers="headersObj"
            :on-remove="handleRemove"
            :on-success="pictureUploadSuccess"
            :file-list="model.iqcNGAttachments"
            :limit="6"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </template>
        <template slot="receivingList">
          <div v-if="model.receivingList && model.receivingList.length > 0">
            <div v-for="(item, index) in model.receivingList" :key="index">
              <!-- <span style="font-size: 16px">{{ '收料记录' + (index + 1) }}：</span> -->
              <div class="demo-input-suffix input-content" style="margin: 0px 0px 10px 10px">
                <span class="fontColor">收货数量:&nbsp;&nbsp;</span>
                <el-input placeholder="收料数量" style="width: 200px; margin-right: 20px" disabled v-model="item.sendExamineQuantity" clearable> </el-input>
                <span class="must fontColor">特采数量:&nbsp;&nbsp;</span>
                <el-input placeholder="请输入特采数量" style="width: 200px" v-model="item.extractionQuantity" clearable> </el-input>
              </div>
            </div>
          </div>
          <div v-else></div>
        </template>
        <!-- <template slot="qmsInspectionAttachmentList">
          <div>
            <div style="display: inline-block; text-align: center" v-for="(item, index) in model.qmsInspectionAttachmentList" :key="item.attachmentId">
              <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)"></el-image>
              <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
            </div>
          </div>
        </template> -->
      </avue-form>
      <div slot="footer" v-if="!propertiesOption.detail">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submit" v-preventReClick>提 交</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add } from '@/api/quality/iqc-defect-handling';
import { mapGetters } from 'vuex';
import index from '../../components/chart/index.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
export default {
  components: {
    index,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'IQC_DEFECT_HANDING',
      form: {},
      model: {},
      timer: new Date().getTime(),
      isIndeterminate: false,
      viewModel: {},
      attachments: [],
      query: { status: 2 },
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      selectData: [],
      badSequenceNumbers: [],
      code: '00',
      checkIqc: true,
      checkbox: false,
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 100,
        searchLabelWidth: 90,
        // searchMenuSpan: 3,
        searchMenuPosition: 'right',
        menuWidth: 200,
        columnBtn: false,
        column: [
          {
            label: '检验单号',
            prop: 'examineNo',
            search: true,
            searchOrder: 1,
            searchSpan: 6,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入检验单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchOrder: 2,
            search: true,
            searchSpan: 6,
            order: 2,
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料名称',
            prop: 'partName',
            searchOrder: 2,
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入物料名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '收料数量',
            prop: 'sendExamineQuantity'
          },
          {
            label: '检验数量',
            prop: 'examineQuantity',
            rules: [
              {
                required: true,
                message: '请输入检验数量',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '检验结果',
          //   prop: 'examineResult',
          //   type: 'select',
          //   searchSpan: 6,
          //   value: 'NG',
          //   dicData: [
          //     {
          //       label: '合格',
          //       value: 'OK'
          //     },
          //     {
          //       label: '不合格',
          //       value: 'NG'
          //     }
          //   ],
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入检验结果',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          // {
          //   label: '供应商编码',
          //   prop: 'vendorCode',
          //   hide: true
          // },
          {
            label: '供应商名称',
            prop: 'vendorName',
            searchOrder: 3,
            search: true,
            searchSpan: 6
          },

          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          // {
          //   label: '检验批次',
          //   prop: 'lotNo'
          // },
          {
            label: '检验方式',
            prop: 'examineMode',
            order: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验人员',
            prop: 'examineByName',
            searchOrder: 3,
            search: true,
            searchSpan: 6
          },
          {
            label: '检验日期',
            prop: 'examineTime',
            search: true,
            searchOrder: 20,
            searchSpan: 6,
            type: 'datetime',
            searchType: 'datetimerange',
            order: 18,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          }
          // {
          //   label: '采购员',
          //   prop: 'creator'
          // }
        ]
      },
      showDialog: false, //IQC检验结果模态框
      fullscreenHandlingDialog: false,
      showViewDialog: false,
      fullscreenViewDialog: false,
      propertiesOption: {
        emptyBtn: false,
        submitBtn: false,
        detail: true,
        group: [
          {
            label: '基础属性',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 160,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '检验单号',
                prop: 'examineNo',
                span: 8,
                disabled: true
              },
              // {
              //   label: '单据号',
              //   prop: 'sourceNo',
              //   span: 8,
              //   disabled: true
              // },
              {
                label: '供应商名称',
                prop: 'vendorCode',
                span: 8,
                disabled: true
              },
              {
                label: '物料编码',
                prop: 'partNo',
                span: 8,
                disabled: true
              },
              {
                label: '物料名称',
                prop: 'partName',
                span: 8,
                disabled: true
              },
              {
                label: '检验方式',
                prop: 'examineMode',
                span: 8,
                type: 'select',
                disabled: true,
                dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                }
              },
              {
                label: '检验人员',
                prop: 'examineByName',
                disabled: true,
                span: 8
              },
              {
                label: '检验日期',
                prop: 'examineTime',
                type: 'date',
                span: 8,
                disabled: true,
                searchType: 'daterange',
                format: 'yyyy-MM-dd',
                valueFormat: 'yyyy-MM-dd',
                startPlaceholder: '开始日期',
                endPlaceholder: '结束日期'
              }
            ]
          },
          {
            label: '检验记录',
            arrow: false,
            prop: 'inspectionInfo',
            labelWidth: 160,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '检验数量',
                prop: 'examineQuantity',
                disabled: true,
                span: 8
              },
              {
                label: '合格数量',
                prop: 'examineOkQuantity',
                disabled: true,
                span: 8
              },
              {
                label: '不良数量',
                prop: 'ngQuantity',
                disabled: true,
                span: 8
              },
              // {
              //   label: '综合判定结果',
              //   prop: 'examineResult',
              //   type: 'radio',
              //   span: 8,
              //   disabled: true,
              //   dicData: [
              //     {
              //       label: '合格',
              //       value: 'OK'
              //     },
              //     {
              //       label: '不合格',
              //       value: 'NG'
              //     }
              //   ]
              // },
              {
                label: '备注',
                prop: 'remark',
                disabled: true,
                span: 12,
                type: 'textarea',
                maxRows: 3,
                minRows: 3
              }
            ]
          },
          {
            label: '不良处理',
            arrow: false,
            prop: 'defectInfo',
            labelWidth: 160,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '处理类型',
                prop: 'disposeType',
                labelWidth: '100',
                span: 20,
                require: true,
                type: 'radio',
                value: 'FULLRETURN',
                dicData: [
                  {
                    label: '批量退货',
                    value: 'FULLRETURN'
                  },
                  {
                    label: '让步收料',
                    value: 'DEVIATION'
                  },
                  {
                    label: '部分特采',
                    value: 'EXTRACTION'
                  }
                ],
                rules: [
                  {
                    required: true,
                    message: '请选择处理类型',
                    trigger: 'blur'
                  }
                ],
                control: (val, form) => {
                  let that = this;
                  if (val == 'FULLRETURN') {
                    // that.model.extractionQuantity = '';
                    return {
                      returnOrSpecialQuantity: { display: true },
                      extractionQuantity: { display: false },
                      sendExamineQuantity: { display: true },
                      receivingList: { display: false }
                    };
                  } else if (val == 'DEVIATION') {
                    that.model.extractionQuantity = that.model.sendExamineQuantity;
                    return {
                      returnOrSpecialQuantity: { display: false },
                      extractionQuantity: { display: true },
                      sendExamineQuantity: { display: true },
                      receivingList: { display: false }
                    };
                  } else if (val == 'EXTRACTION') {
                    return {
                      returnOrSpecialQuantity: { display: false },
                      extractionQuantity: { display: false },
                      sendExamineQuantity: { display: false },
                      receivingList: { display: true }
                    };
                  }
                }
              },
              {
                label: '收料数量',
                prop: 'sendExamineQuantity',
                span: 8,
                disabled: true
              },
              {
                label: '退货数量',
                prop: 'returnOrSpecialQuantity',
                span: 8,
                disabled: true
              },
              {
                label: '实收数量',
                prop: 'extractionQuantity',
                disabled: true,
                span: 8
              },
              {
                label: '',
                labelWidth: '80',
                prop: 'receivingList',
                formslot: true,
                display: false,
                span: 20
              },
              // {
              //   label: '处理报告',
              //   prop: 'iqcNGAttachments',
              //   type: 'upload',
              //   span: 20,
              //   row: true,
              //   loadText: '文件上传中，请稍等',
              //   propsHttp: {
              //     url: 'link',
              //     name: 'originalName',
              //     res: 'data',
              //     attachId: 'attachId'
              //   },
              //   limit: 6,
              //   action: '/api/blade-resource/oss/endpoint/put-file-attach',
              //   rules: [
              //     {
              //       required: true,
              //       message: '请上传IQC检验报告',
              //       trigger: 'blur'
              //     }
              //   ]
              // },
              // {
              //   label: '处理报告',
              //   prop: 'qmsInspectionAttachmentList',
              //   listType: 'picture',
              //   type: 'upload',
              //   span: 24
              // },
              {
                label: '备注',
                prop: 'disposeRemark',
                span: 12,
                type: 'textarea',
                maxRows: 3,
                minRows: 3,
                row: true,
                rules: [
                  {
                    message: '请填写备注',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.iqcDefectHandling_detail, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    handleRemove(file, fileList) {
      this.model['iqcNGAttachments'] = fileList;
    },
    pictureUploadSuccess(res) {
      if (!this.model.iqcNGAttachments) {
        this.model.iqcNGAttachments = [];
      }
      this.model['iqcNGAttachments'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        name: res.data.originalName
      });
    },
    async submit() {
      let attribute = this.model;
      /*******************************特采******************************/
      let flag;
      if (this.model.receivingList && this.model.receivingList.length > 0) {
        flag = this.model.receivingList.some((item) => {
          return item.extractionQuantity == null || item.extractionQuantity == undefined || item.extractionQuantity == '';
        });
        if (attribute.disposeType === 'EXTRACTION' && flag) {
          for (let i = 0; i < this.model.receivingList.length; i++) {
            let reg = /^\?+[0-9]\d*$/; //匹配整数
            if (!reg.test(Number(this.model.receivingList[i].extractionQuantity))) {
              this.$message({
                type: 'warning',
                message: '特采数量需大于等于0'
              });
              return;
            }
          }
        }
      }
      if (attribute.disposeType === 'EXTRACTION' && flag) {
        this.$message({
          type: 'warning',
          message: '特采数量为必填项，请输入!'
        });
        return;
      }

      let extractionQuantity = this.model.receivingList.reduce((prev, cur) => {
        return prev + Number(cur.extractionQuantity);
      }, 0);

      let sendExamineQuantity = this.model.receivingList.reduce((prev, cur) => {
        return prev + Number(cur.sendExamineQuantity);
      }, 0);
      if (attribute.disposeType === 'EXTRACTION' && extractionQuantity > sendExamineQuantity) {
        this.$message({
          type: 'warning',
          message: '特采数量不可超过收料数量!'
        });
        return;
      }
      this.$refs.badhandlingProperties.validate((valid, done) => {
        if (valid) {
          // let attribute = this.model;

          // let attachments = attribute.iqcNGAttachments.map((attachment) => {
          //   return {
          //     link: attachment.link,
          //     attachmentId: attachment.attachmentId,
          //     attachmentType: 'INSPECTION',
          //     attachmentName: attachment.originalName
          //   };
          // });
          //合并待检上传的图片
          // attribute.qmsInspectionAttachmentList = attribute.qmsInspectionAttachmentList.concat(attachments);
          // attribute.status = 3;
          if (attribute.disposeType === 'EXTRACTION') {
            //特采
            attribute.extractionQuantity = extractionQuantity;
            attribute.disposeQuantity = Number(attribute.sendExamineQuantity) - extractionQuantity;
          } else if (attribute.disposeType === 'DEVIATION') {
            //让步
            attribute.extractionQuantity = attribute.sendExamineQuantity;
            attribute.disposeQuantity = 0;
          } else {
            //批量
            attribute.disposeQuantity = attribute.sendExamineQuantity;
            attribute.extractionQuantity = 0;
          }
          let params = {
            id: attribute.id,
            disposeType: attribute.disposeType,
            disposeQuantity: attribute.disposeQuantity,
            extractionQuantity: attribute.extractionQuantity,
            remark: attribute.disposeRemark
          };
          add(params).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.$refs.badhandlingProperties.resetForm();
              this.showDialog = false;
            },
            (error) => {
              window.console.log(error);
            }
          );
          done();
        }
      });
    },

    //只能输入正整数
    changeValue(value) {
      if (this.model.extractionQuantity.length == 1) {
        value = value.replace(/[^1-9.]/g, '');
      } else {
        value.replace(/\D/g, '');
      }
      this.model.extractionQuantity = value;
      return value;
    },
    //限制不能输入小数点
    keypressOverlimitRate(e) {
      let code = e.keyCode;
      if (code === 46) {
        e.preventDefault();
      }
    },

    cancel() {
      this.showDialog = false;
      this.model = {};
    },
    cancelView() {
      this.showViewDialog = false;
      this.viewModel = {};
      this.attachments = [];
    },

    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = { status: 2 };
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.examineTime && params.examineTime.length > 0) {
        params.examineStartTime = params.examineTime[0];
        params.examineEndTime = params.examineTime[1];
      }
      delete params.examineTime;
      this.query = params;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.documentType = 'IQC';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.data.forEach((item) => {
          item.examineResult = 'NG';
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    //不良处理
    async badHandling(id) {
      this.propertiesOption.detail = false;
      let defectInfo = this.findNode(this.propertiesOption.group, 'defectInfo');
      // let qmsInspectionAttachmentList = this.findObject(defectInfo.column, 'qmsInspectionAttachmentList');
      // let iqcNGAttachments = this.findObject(defectInfo.column, 'iqcNGAttachments');
      // qmsInspectionAttachmentList.display = false;
      // iqcNGAttachments.display = true;
      this.fullscreenHandlingDialog = false;
      this.detailRequest(id, 'handing');
      this.showDialog = true;
    },
    async view(id) {
      this.propertiesOption.detail = true;
      let defectInfo = this.findNode(this.propertiesOption.group, 'defectInfo');
      // let qmsInspectionAttachmentList = this.findObject(defectInfo.column, 'qmsInspectionAttachmentList');
      // let iqcNGAttachments = this.findObject(defectInfo.column, 'iqcNGAttachments');
      // qmsInspectionAttachmentList.display = true;
      // iqcNGAttachments.display = false;
      this.fullscreenViewDialog = false;
      this.detailRequest(id, 'view');
      this.showDialog = true;
    },
    detailRequest(id, type) {
      getDetail(id).then((res) => {
        let data = res.data.data || {};
        this.model = {
          ngQuantity: Number(data.examineQuantity || 0) - Number(data.examineOkQuantity || 0),
          examineResult: 'NG',
          ...data,
          disposeType: type === 'handing' ? 'FULLRETURN' : data.disposeType,
          receivingList: [{ sendExamineQuantity: data.sendExamineQuantity, extractionQuantity: '' }]
        };
        // this.model.qmsInspectionAttachmentList = data.attachments || [];
        if (type === 'handing') {
          this.model.returnOrSpecialQuantity = this.model.sendExamineQuantity;
        }
      });
    },
    findNode(list = [], prop) {
      let node;
      list.forEach((ele) => {
        if (ele.prop === prop) node = ele;
      });
      return node;
    },
    newKey() {
      this.timer = new Date().getTime();
    },

    closeDialog() {
      this.$refs.badhandlingProperties.resetForm();
    },
    handleDownload(item) {
      window.open(`${item.link}`);
    },

    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
.iqc-placeholder {
  font-size: $size;
  color: #aaaaaa;
}

.iqcDialog {
  ::v-deep input[type='file'] {
    display: none !important;
  }
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
.input-content {
  display: flex;
  flex-direction: row;
}
.must::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.fontColor {
  color: #606266;
}
</style>
